const { src, dest, parallel, series, watch } = require('gulp')
// 压缩css文件
const cleanCSS = require('gulp-clean-css')
// 对文件重命名
const rename = require('gulp-rename')
// 解决兼容性问题
const autoprefixer = require('gulp-autoprefixer')
// 将ES6+ 转换为 ES5
const babel = require('gulp-babel')
// 压缩JS文件
const uglify = require('gulp-uglify')
// 页面文件
const htmlmin = require('gulp-htmlmin')
// 图片压缩
const imagemin = require('gulp-imagemin')
// 文件清除
const del = require('del')
// 开发服务器
const browserSync = require('browser-sync').create()

// 构建样式文件
const style = () => {
  return src('src/css/*.css', { base: 'src' })
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(rename({ extname: '.min.css' }))
    .pipe(dest('dist'))
}

// 构建脚本文件
const script = () => {
  return src('src/js/index.js', { base: 'src' })
    .pipe(babel({
      presets: ['babel-preset-env']
    }))
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(dest('dist'))
}

const other = () => {
  return src('src/js/*.js', { base: 'src' })
    .pipe(dest('dist'))
}

// 构建页面文件
const html = () => {
  return src('src/*.html')
    .pipe(htmlmin({ 
      collapseWhitespace: true,
      minifyJS: true
    }))
    .pipe(dest('dist'))
}

// 构建图片文件
const image = () => {
  return src('src/images/**', { base: 'src' })
    .pipe(imagemin())
    .pipe(dest('dist'))
}
// 清除文件
const delet = () => {
  return del(['dist'])
}
// 开发服务器
const serve = () => {
  watch('src/index.html', html)
  watch('src/css/*.css', style)
  watch('src/js/*.js', script)
  watch('src/images/**', image)

  browserSync.init({
    notify: false,
    files: 'dist/**',
    server: {
      baseDir: './dist',
      // routes: {
      //   '../node_modules ': 'node_modules'
      // }
    }
  })
}

// 构建任务组合
const build = parallel(style, script, other, html, image)
const dev = series(delet, build, serve)
module.exports = {
  dev
}